local redis = require "resty.redis"

local function connect_redis()
    local rds = redis.new()

    rds:set_timeout(1000)

    local ok, err = rds.connect(rds, '10.164.5.160', 6379)

    if not ok then
        ngx.say("failed to connect:", err)

        return false
    end

    local counts, err = rds:get_reused_times()

    if counts <= 0 then
        local red, err = rds:auth("C@pitaland123")

        if not red then
            ngx.say("failed to authenticate: ", err)

            return false
        end
    end

    return rds
end

local function close_redis(rds)
    if not rds then
        return
    end

    local ok, err = rds:set_keepalive(10000, 100)

    if not ok then
        ngx.say("failed to close:", err)

        return
    end
end

local rds = connect_redis()
local ssid = ngx.var.cookie_ssid
local enable_gray = rds:get('enable-gray')
local intercept = rds:sismember('gray-users', ssid)

ngx.header['Strict-Transport-Security'] = 'max-age=63072000; includeSubdomains; preload'

if (intercept == 1 and enable_gray == 'on') then
    ngx.header["site-mode"] = 'on gray'

    ngx.exec("@grayProxy")

    close_redis(rds)

    return
end

ngx.exec("@proxy")

close_redis(rds)
